package com.lgCore.client.workHandler;

import com.lgCore.netty.client.NettyClientBootstrap;
import com.lgCore.netty.message.Constants;
import com.lgCore.netty.message.LoginMsg;
import com.lgCore.util.ExceptionUtil;
import com.lgCore.util.IpAddr;
import com.lgCore.util.StringUtils;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.AttributeKey;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务端连接池管理类
 */
public class ClientNettyBootStrapPool {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClientNettyBootStrapPool.class);

    //存放nettyChannel信息
    protected static ConcurrentHashMap<String, NettyClientBootstrap> serverChannelHashMap =
            new ConcurrentHashMap<String, NettyClientBootstrap>();

    //管道存放共享数据
    public final static AttributeKey<Constants> auth = AttributeKey.valueOf("auth");

    /**
     * 查询连接池信息
     */
    public static NettyClientBootstrap getChannelByIpAddr(String ipAddr) {
        if (StringUtils.isNullOrEmpty(ipAddr)) {
            return null;
        }
        if (serverChannelHashMap.get(ipAddr) == null) {
            String[] strs = ipAddr.split(":");
            //rpc客户端
            NettyClientBootstrap clientBootstrap = null;
            try {
                clientBootstrap = new NettyClientBootstrap(Integer.parseInt(strs[1]), strs[0]);
//                //发送心跳连接
//                LoginMsg loginMsg = new LoginMsg();
//                clientBootstrap.getSocketChannel().writeAndFlush(loginMsg);
                //记录服务端连接信息
                serverChannelHashMap.put(ipAddr, clientBootstrap);
                //发送心跳 睡眠500毫秒
                Thread.sleep(500);
                return clientBootstrap;
            } catch (InterruptedException e) {
                String errorMsg = ExceptionUtil.ExceptionDetailAll(e);
                LOGGER.info("连接失败 "+errorMsg);
                LOGGER.error("连接失败：" + e.getMessage());
//                return null;
                e.printStackTrace();
            }
        }
        return serverChannelHashMap.get(ipAddr);
    }

    public static String getKey(String ip, int port) {
        return ip + ":" + port;
    }
    /**
     * @param ipAddr 127.0.0.1:8888
     */
    public static void delKey(String ipAddr) {
        serverChannelHashMap.remove(ipAddr);
    }
}

